from __future__ import with_statement

import sys
import math
import time
import itertools
import os.path
import logging
import shutil
import glob
import optparse

import refolding
import refolding_common

logger = logging.getLogger("refolding_copy_curves")
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)

def _create_dir_or_warn(dir_path):
    if os.path.exists(dir_path):
        logger.warning("%s already exists.", dir_path)
    else:
        os.mkdir(dir_path)

def copy_selected_curves(source_root_dir, target_root_dir, name):
    data_dir = os.path.join(source_root_dir, "refolding_target_%s" % name)
    if not os.path.exists(data_dir):
        raise Exception("%s does not exist.", data_dir)
    source_jp_dir = os.path.join(source_root_dir, "refolding_jp_%s" % name)
    if not os.path.exists(source_jp_dir):
        raise Exception("%s does not exist.", source_jp_dir)
    source_cps_dir = os.path.join(source_root_dir, "refolding_cps_%s" % name)
    if not os.path.exists(source_cps_dir):
        raise Exception("%s does not exist.", source_cps_dir)
    selected = refolding_common.read_entries(
        os.path.join(target_root_dir, name + ".txt"))
    selected_dir = os.path.join(target_root_dir, "refolding_selected_%s" % name)
    _create_dir_or_warn(selected_dir)
    selected_jp_dir = os.path.join(target_root_dir, "refolding_jp_%s" % name)
    _create_dir_or_warn(selected_jp_dir)
    selected_cps_dir = os.path.join(target_root_dir, "refolding_cps_%s" % name)
    _create_dir_or_warn(selected_cps_dir)
    for entry in selected:
        if isinstance(entry, tuple):
            data_filename = refolding_common.data_filename(entry[-1])
            # copyfile does not copy any metadata
            shutil.copyfile(
                os.path.join(data_dir, data_filename),
                os.path.join(selected_dir, data_filename))
            shutil.copyfile(
                os.path.join(source_jp_dir, data_filename + ".junctionPoints"),
                os.path.join(selected_jp_dir, data_filename + ".junctionPoints"))
            shutil.copyfile(
                os.path.join(source_cps_dir, data_filename + ".cps"),
                os.path.join(selected_cps_dir, data_filename + ".cps"))

def main(params):
    parser = optparse.OptionParser()
    parser.add_option(
        "--source_root_dir", help="dir having under it junction points and data directories")
    parser.add_option(
        "--target_root_dir", help="dir having under it .txt files")
    options, args = parser.parse_args(params)
    if args:
        parser.print_help()
        return -1
    print(options)

    source_root_dir = options.source_root_dir
    target_root_dir = options.target_root_dir
    for filepath in glob.iglob(os.path.join(target_root_dir, "*.txt")):
        name = os.path.basename(os.path.splitext(filepath)[0])
        copy_selected_curves(source_root_dir, target_root_dir, name)

if __name__ == "__main__":
    main(sys.argv[1:])
